package com.botao.service;

import com.botao.dao.ClassesDao;
import com.botao.dao.StudentDao;
import com.botao.pojo.Page;
import com.botao.pojo.Student;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImpl implements StudentService {

    static Logger logger = Logger.getLogger(StudentServiceImpl.class);

    @Autowired
    @Qualifier("mybatisClassesDao")
    ClassesDao classesDao;
    @Autowired
    @Qualifier("jdbcStudentDao")
    StudentDao studentDao;

    @Override
    public boolean add(Student student) {
        int add = 0;
        try {
            String banji = student.getBanji();
            int banJiId = classesDao.getClassesIdByBanJi(banji);
            student.setBanjiId(banJiId);
            add = studentDao.add(student);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return add >= 1;
    }

    @Async("serviceThreadPool")
    @Override
    public void delete(String id) {
        studentDao.delete(id);
    }

    @Override
    public void update(Student student) {
        String banji = student.getBanji();
        int banJiId = classesDao.getClassesIdByBanJi(banji);
        student.setBanjiId(banJiId);
        studentDao.update(student);
    }

    @Override
    public Page<Student> listStudent(Long currentPage, Long pageSize) {
        List<Student> studentList = studentDao.listStudent(currentPage, pageSize);
        Long count = studentDao.count();
        Long totalPage = (count + pageSize - 1) / pageSize;
        return new Page<Student>(studentList, currentPage, pageSize, totalPage, count);
    }

    @Override
    public Student getOne(String id) {
        return studentDao.getOne(id);
    }

    @Override
    public Student searchStudent(String id) {
        if (id == null || "".equals(id)) {
            return null;
        }
        return studentDao.searchStudent(id);
    }

    @Override
    public List<Student> getStudentsByClassesId(int id) {
        return studentDao.getStudentsByClassesId(id);
    }

    @Override
    public boolean studentExists(String id) {
        return studentDao.studentExists(id);
    }
}
